# -*- coding: UTF-8 -*-
"""
@auth:buxiangjie
@date:2022/2/10 14:09
@describe: 
"""
import allure
import pytest
import requests
import time
import json
from log.ulog import logger_
from common.common_func import Common


def pytest_addoption(parser):
	parser.addoption("--env", default="qa", choices=["qa", "test"], help="运行环境")
	parser.addoption("--operator", default="local", type=str, help="操作用户")


def pytest_configure(config):
	global batch, parse_
	batch = str(time.time()).replace(".", "")

	parse_ = {
		"operator": str(config.getoption("--operator")).replace(" ", ""),
		"env": config.getoption("--env")
	}


@pytest.fixture(scope="session")
@allure.step("获取外部参数")
def parse() -> dict:
	return parse_


@pytest.fixture(scope="session")
@allure.step("获取各种枚举")
def drop_down_box_content() -> dict:
	api_info = Common.get_json_data("/config/mart_api_temp", f"config_drop_down_box_content.json")
	rep = Common.response(
		addr=api_info["addr"],
		env=parse_["env"],
		headers=api_info["headers"],
		method=api_info["method"],
		service="mart",
		param=api_info["param"]
	)
	return rep["content"]


@pytest.mark.hookwrapper
def pytest_runtest_makereport(call):
	outcome = yield
	report = outcome.get_result()
	if parse_["operator"] != "local":
		if report.when == "call":
			detail = {
				"batch_id": batch,
				"case_name": report.location[2].split("[")[0],
				"status": report.outcome,
				"step": report.when,
				"operator": parse_["operator"],
				"run_time": time.strftime("%Y-%m-%d", time.localtime()),
				"script": "saas_api"
			}
			if report.passed is False:
				detail["exception_name"] = call.excinfo.typename

			logger_.info(f"上传用例执行结果:{detail}")
			rep = requests.post(
				url="http://172.17.205.215:8817/statistics/runcase_detail",
				json=json.loads(json.dumps(detail, ensure_ascii=False).encode("utf-8"))
			)
			logger_.info(f"上传用例执行结果接口响应:{rep.text}")
